/**
 * 创建自定状态跟踪绑定: 避免预定义
 * 例如:
 *   {
 *     data(){
 *       return {
 *        form: createState({search:{}})
 *      }
 * 
 * @author xiufu.wang  
 */
import Vue from 'vue'

const dp = Object.defineProperty
const gpd = Object.getOwnPropertyDescriptor

function createSyncMircTask(preKeys, getObj){
    Promise.resolve(null).then(() => {
        const obj = getObj()
        const objectKeys = Object.keys(obj)
        const hasKeysChange = preKeys.join('') !== objectKeys.join('')
        if (!hasKeysChange) { 
            return
        }
        
        //绑定状态
        objectKeys.forEach(k => {
            Vue.util.defineReactive(obj, k, obj[k])
        })

        //更新
        if (obj.__ob__) {
            obj.__ob__.dep.notify()
        }
    })
}


export default function (sateDefs) {
    sateDefs = sateDefs || {}
    Object.keys(sateDefs).forEach(k => {
        let value = sateDefs[k]
        if (value && typeof value === 'object' && value._ignore !== true) {
            dp(sateDefs, k, {
                configurable: true,
                enumerable: true,
                get: function () {
                    // 跟踪结构是否变化
                    createSyncMircTask(Object.keys(value), () => value, k)
                    return value
                },
                //不允许修改
                set: function (v) { 
                    value = v
                }
            })
        }
    })
    return sateDefs
}
